<?php defined('SYSPATH') or die('No direct script access.');
/**
* @package Fatima Purple Project <FPP>
* @author Erik Beltran Estelita <WindMaker> <hunk4ths@gmail.com>
* @description Crud Model & ORM for Kohana :)
* @license MIT
* @date lun nov  9 23:34:36 PET 2009
*/
// Nota los models deben ser  compatibles con el sistema de i18n de Kohana
class fpp_Model extends Model {
  protected $list_display = NULL;
  protected $list_filter = NULL;
  protected $ordering = NULL;
  protected $search_fields = NULL;
  protected $items = 10;
  protected $edit = FALSE;
  protected $delete = FALSE;
  protected $add = FALSE;
  protected $save = "AUTO";
  protected $show = "AUTO";
  protected $_Table = NULL;
  public $templatedir = NULL;
  public $_FirstPrimary = NULL;
  public $_TabView = FALSE;
  public $GetFieldAjax = NULL; //obtiene un campo con ajax :)
  
  public function __construct(){
    @session_start();
    parent::__construct();
    $this->_FirstField  = null;
    if($this->_Table == null){
      $this->_Table = str_replace(array("fpp_", "_Model"), "", get_class($this));
    }
    list ($keyf) = each($this->meta);
    $this->_FirstPrimary = $keyf;
    $this->LoadMetas();
    $this->result = new StdClass();
    $this->result->ListTable = null;
    $this->result->ListTotal = null;
    $this->result->ListFilter = null;
    $this->result->ListFilterBox = null;
    $this->result->ListPagination = null;
    $this->result->ListFilterBox = null;
    $this->_FilterActive = null;
    $this->_FilterBoxresult = null;    
    $this->_AddField = null;
    $this->_ShowID = FALSE;
    $this->_AddKeyField = null;
    $this->_ApplyPHP = FALSE;
    $this->_ApplyPHPCode = null;
    $this->_ApplyPHPFields = null;
    $this->_messagesys = null;
    $this->_OnlyRead = FALSE;
    $this->_File_i18n = NULL;
    $this->_Response = NULL;
    $this->set_base_uri();
    $this->templatedir = $this->templatedir == NULL ? 'tablelist/' : $this->templatedir;
  }
  /*
  public function RemoveMeta($metaKey){
    $this->meta[$metaKey] = ''
  }
  */
  public function LoadMetas(){
    if($this->list_display == NULL){
      foreach($this->meta as $field => $value){
        if($this->_FirstField == null){
          $this->_FirstField = $field;
        }
        $this->list_display[] = $field;
      }
    }
  }
  
  public function GetSpace($key = null){
    return ":P";
  }
  
  public function set_property($property,$value){
    $this->$property = $value;  
  }
  public function set_base_uri($uristr = null){
    $ext_uri = '/'.'fpp_actions/tbl_'.$this->_Table.'/';
    if($uristr <> null){
     $this->base_uri = $uristr.$ext_uri;
     return true;
    }
    $uri = new Uri;
    $uri_string = $uri->string();
    $urixplode = explode('fpp_actions',$uri_string);
     $this->base_uri = $uri_string.$ext_uri;
    if(count($urixplode)>1){
      $this->base_uri = $urixplode[0].$ext_uri;
    }
  }
  
  public function apply_filter($filter,$value){
    $this->_FilterActive[$filter][$value] = TRUE;
    $this->_FilterActiveByInfo[$filter] = $value;
    $this->list_filter[$filter] = $filter;
    return TRUE;
  }
  
  public function ListTable(){
    $fields = new fpp_fieldtype_Model($this->meta);
    $fields = $fields->fields;
    $arrayWhere = null;
    $select = null;
    $arrayTables[] = $this->_Table;    
    $input = Input::instance();
//Construccion de los objetos ademas del SELECT, FROM y WHERE Inicial
    $ldcount = 0;
    $check_delete = $input->get('check_delete');
    $EliminarSel = $input->get('EliminarSel');
    if(is_array($check_delete) and $EliminarSel <> ""){
      foreach($check_delete as $check_delete_id => $check_delete_value){
        $this->deleterow($check_delete_id);
      }
    }

    foreach($this->list_display as $fieldname){
        if($this->_FirstField == null){
          $this->_FirstField = $fieldname;
        }
        $object = $fields->$fieldname;
        $db_field = "{$this->_Table}.{$fieldname}";
        if($object->typefield <> 'OneToMany'){
          $select[] = $db_field;
          $titles[] = ($this->_File_i18n == null) ? $object->verbose : Kohana::lang($this->_File_i18n.'.'.$object->verbose);
        }else{
          unset($this->list_display[$ldcount]);
        }
        $choice[$fieldname] = $object->choices;
        if($object->db_value <> null and $this->_ShowID == FALSE){
          $db_value = "{$object->db_table}.{$object->db_value}";
          $select[] = $db_value;
          $select[] = "{$object->db_table}.{$object->db_label}"; 
          $arrayTables[$object->db_table] = $object->db_table;
            $arrayWhere[$db_field] = "`{$this->_Table}`.`{$fieldname}`=`{$object->db_table}`.`{$object->db_value}`";
          $move[$fieldname] = $object->db_label;
        }
        $ldcount++;
    }
    
    if($this->_AddField <> null){
      foreach($this->_AddField as $data){
        $table_add = $data['table'];
        $field_add = $data['field'];
        $key_add   = $data['key'];
        $select[] = "{$table_add}.{$field_add}";
        $key_local   = $data['localkey'];
        $arrayWhere[$key_local] = "`{$this->_Table}`.`{$key_local}`=`{$table_add}`.`{$key_add}`";
        $arrayTables[$table_add] = $table_add;
        $this->list_display[] = $field_add;
      }
    }
    
//Inicializacion del query
    $strinTables = implode(',',$arrayTables);
    $select = implode(',',$select);
    $uri = new Uri;
    $minuspages = (integer) $this->items;
    $page = ($uri->segment('page') * $this->items) - $minuspages;
    $page = ($page < $this->items) ? 0 : $page;
    $query = $this->db->select($select)->from($strinTables);
    if($this->items <> 'ALL'){
     $query = $query->limit($this->items,$page);
    }
    if(is_array($arrayWhere)){
      $stringWhere = implode(' AND ',$arrayWhere);
      $query = $query->where($stringWhere);
    }
//where de filtros de los checkbox
    $arrayORWhere = null;
    $arrayANDORWhere = null;
    $valuememory = null;
    if($this->list_filter <> null){
      foreach($this->list_filter as $value){
        $filter_value = isset($this->_FilterActive[$value]) ? 
          $filter_value = $this->_FilterActive[$value] :
            $input->get($this->_Table.'_'.$value);
        if(isset($filter_value)){
          foreach($filter_value as $idvalcheck => $valcheck){
            $arrayORWhere = ($valuememory <> $value) ? null : $arrayORWhere;
            $valuememory = $value;
            $arrayORWhere[] = "`{$this->_Table}`.`{$value}`= '$idvalcheck'";
            $stringWhere = (is_array($arrayORWhere)) ? implode(' OR ',$arrayORWhere) : $stringWhere;
          }
        }
        if(isset($stringWhere)){
          $arrayANDORWhere[] = "({$stringWhere})";
        }
      }
    }
    if(is_array($arrayANDORWhere)){
      $stringWhere = implode(' AND ',$arrayANDORWhere);
      $query = $query->where("($stringWhere)");
    }

// Like de busqueda de texto
    if(@$this->_FilterBoxresult[$this->_Table.'_input']<>''){
      if($this->search_fields <> null){    
        foreach($this->search_fields as $value){
          $strw[] = "`{$this->_Table}`.`{$value}` like '%".addslashes($this->_FilterBoxresult[$this->_Table.'_input'])."%'";
        }
        $strw = implode(' OR ',$strw);
        $query = $query->where(new Database_Expression(" ( $strw ) "));
      }
    }
//Ordenamiento del query
    if($this->ordering <> null){
      foreach($this->ordering as $sort){
        $simbol = substr($sort, 0,1);
        $sortval = substr($sort, 1);
        $ordernat = ($simbol == '+') ? 'ASC' : 'DESC';
        $ordering = array($sortval=>$ordernat);
      }
      $query = $query->orderby($ordering);
    }
    try {
     $query = $query->get();
    } catch (Exception $e) {
                    echo Kohana::debug('Error: ' ."\n".  $e->getMessage(). "\n");
                    die();
    }

//Conteo de total retornado Count(*)
     $this->GetTotalLastQuery();
/* Template */        
        $init_1 = 0;
        $data = null;
        foreach($query as $row){
          $init_2 = 0;
          foreach($this->list_display as $key){
            if(@$move[$key]<>''){
              $key = $move[$key];
            }
            $value = $row->$key;
            if(@$choice[$key] <> null){
               $value = @$choice[@$key][@$value];
            }
            $data[$init_1]->$key=$value;
            $init_2++;
          }
          $init_1++;
        }
/* Fin Template */   
    $view = new View($this->templatedir.'list');
    $view->set('data',$data);
    $view->set('titles',$titles);
    $view->set('pagination',$this->result->ListPagination);
    $view->set('total',$this->result->ListTotal);
    $view->set('edit',$this->edit);
    $view->set('read',$this->_OnlyRead);
    $view->set('delete',$this->delete);
    $view->set('first_field',$this->_FirstField);
    $view->set('base',$this->base_uri);
    $this->result->ListTable = $view->render();
    unset($view,$init_1,$init_2,$move,$data,$titles,$query,$strinTables,$select,$arrayTables,$arrayWhere,$object,$fields,$db_field,$key,$value,$data);
    return TRUE;
  }

  public function ListFilter(){
    if($this->list_filter == null or $this->_FilterActive <> null){
      return FALSE;
    }
    $str = null;
    $fields = new fpp_fieldtype_Model($this->meta);
    $fields = $fields->fields;
    $input = Input::instance();    
    foreach($this->list_filter as $value){
    $fname = "{$this->_Table}_{$value}";
    $fname_value = $input->get($fname);
      $object = $fields->$value;
      $checkres = null;
      if($object->choices == null){
      try {
              $result =$this->db->from($object->db_table)->select(array($object->db_value.' as value',$object->db_label.' as label'))->get();
      } catch (Exception $e) {
                    echo Kohana::debug('Error: ' ."\n".  $e->getMessage(). "\n");
                    die();
      }

        foreach($result as $row){
          $checkres .= "<p>".form::checkbox("{$this->_Table}_{$value}[{$row->value}]",TRUE,@$fname_value[$row->value])."{$row->label}</p>";
        }
      }else{
        $checkres = fpp::CheckboxGroup("{$this->_Table}_$value",$object->choices,@$fname_value);
      }
      $verbose = ($this->_File_i18n == null) ? $object->verbose : Kohana::lang($this->_File_i18n.'.'.$object->verbose);
      $str .= View::factory($this->templatedir.'filters')
              ->set('title',$verbose)
              ->set('class',$value)
              ->set('checks',$checkres)
              ->render();
    }
    $this->result->ListFilter = $str;
    return TRUE;
  }
  
  public function ListFilterBox(){
    if($this->search_fields == null){
      return TRUE;
    }
    $fname = $this->_Table.'_input';
    $input = Input::instance();
    $fname_value = $input->get($fname);
    $this->result->ListFilterBox = "<p> Buscar : ".form::input($fname,$fname_value).'<p>';
    $this->_FilterBoxresult = $input->get();
    return TRUE;
  }
  
  public function blocklist($tablelist=TRUE){
    $view = new View($this->templatedir.'block');
    if($this->result->ListFilter == null){
      $this->ListFilter();
    }
    if($this->result->ListFilterBox == null){
      $this->ListFilterBox();
    }
    if($this->result->ListTable == null){
      $this->ListTable();
    }
    $view->set('tablelist',$this->result->ListTable);
    $view->set('total',$this->result->ListTotal);
    $view->set('filters',$this->result->ListFilter);
    $view->set('filterbox',$this->result->ListFilterBox);
    $view->set('add',$this->add);
    $view->set('msg',$this->_messagesys);
    $view->set('response',$this->_Response);
    $view->set('dir_img',Kohana::config('fpp_config.directory_images'));
    $view->set('pagination',$this->result->ListPagination);
    $view->set('base',$this->base_uri);
    $this->_messagesys = null;
    return $view->render();
  }
  
  
  private function GetTotalLastQuery(){
     $tot = 0;
     $sqlcomplete = $this->db->last_query();
     $sqlcomplete = explode('FROM',$sqlcomplete,2);
     if(count($sqlcomplete)>1){
       $sqlcomplete = $sqlcomplete[1];
       $sqlcomplete = explode('ORDER BY',$sqlcomplete,2);
       $sqlcomplete = explode('LIMIT',$sqlcomplete[0],2);
       $sqlcomplete = " FROM ".$sqlcomplete[0];
     }else{
      $sqlcomplete = null;
     }
     $query = $this->db->query('SELECT count(*) as Total '.$sqlcomplete);
     foreach($query as $row){
      $tot = $row->Total;
     }
     $this->result->ListTotal = $tot;
     $pagination = new Pagination(array(
          // 'base_url'    => 'welcome/pagination_example/page/', // base_url will default to current uri
          'uri_segment'    => 'page', // pass a string as uri_segment to trigger former 'label' functionality
          'total_items'    => $tot, // use db count query here of course
          'items_per_page' => $this->items, // it may be handy to set defaults for stuff like this in config/pagination.php
          'style'          => 'digg' // pick one from: classic (default), digg, extended, punbb, or add your own!
      ));
     $this->result->SqlOffset = $pagination->sql_offset;
     $this->result->ListPagination = $pagination;
  }
  
  public function autoblock(){
    $uri = new Uri;
    $table = $uri->segment('fpp_actions');
    if("tbl_".$this->_Table == $table){
      $action = $uri->segment($table);
      $id = $uri->segment($action);
      if($this->_OnlyRead == TRUE){
        if($action == "read" ){
          return $this->blockfields($id);
        }
      }else{
        if($action == "edit"){
          return $this->blockfields($id);
        }
        if($action == "ajax"){
          $field = $uri->segment('ajaxfield');
          $this->GetFieldAjax = $field;
          if($id == 0){
            $id = null;
          }
          return $this->blockfields($id);
        }
        if($action == "add"){
          return $this->blockfields(null);
        }
  
        if($action == "delete"){
          $this->deleterow($id);
          $this->_messagesys = fpp::fppmsg('Item eliminado correctamente');
        }
      }
    }
    return $this->blocklist();
  }

  public function deleterow($id = null){
    if($id == null){
      return false;
    }
    $items = $this->show;
    $first = null;
//construccion de qu campos se van a mostrar
    if($items == "AUTO"){
      $items = array();
      foreach($this->meta as $fieldname => $props){
        $first = $fieldname;
        break;
      }
    }
//cargando las propiedades de cada campo 
    foreach($items as $fieldname ){
        $first = $fieldname;
        break;
    }
    $this->db->delete($this->_Table, array($first => $id));
  }
  
  public function blockfields($id = null){
    $idorigin = $id;
    if($id <> null){
      settype($id,'integer');
    }
    if($id === 0 and $idorigin<>'LOOK'){
      return NULL;
    }
    $msg = null;
    $types = new fpp_fieldtype_Model($this->meta);
    $types->SetPkID($id);
    $types->AddAttributes('NameModel',get_class($this));
    $types->AddAttributes('Primary',$this->_FirstPrimary);
    $fields = &$types->fields;
    $this->_apply_php($types);
    $arrayWhere = null;
    $select = null;
    $arrayTables[] = $this->_Table;
    $first = null;
    $items = $this->show;        
    $OneToMany = array();
//construccion de qu campos se van a mostrar
    if($items == "AUTO"){
      $items = array();
      foreach($this->meta as $fieldname => $props){
        $items[] = $fieldname;
      }
    }
//cargando las propiedades de cada campo
    $OTMSelect = array();
    foreach($items as $fieldname ){
      if($first == null){
        $first = $fieldname;
      }
        $object = $fields->$fieldname;
          $db_field = "{$this->_Table}.{$fieldname}";
          if($object->typefield <> 'OneToMany'){
            $select[] = $db_field;
          }else{
            $OTMSelect[] = $fieldname;
          }
          $titles[$fieldname] = ($this->_File_i18n == null) ? $object->verbose : Kohana::lang($this->_File_i18n.'.'.$object->verbose);
          $choice[$fieldname] = $object->choices;


    }
    if($this->_AddField <> null){
      foreach($this->_AddField as $data){
        $table = $data['table'];
        $db_field = "$table.{$data['field']}";
        $select[] = $db_field;
        $arrayTables[$table] = $table;
      }
    }

//si es post , grabara los cambios
    if(request::method() == 'post' and $this->_OnlyRead == FALSE){
      $save = $this->save;
      if($save == 'AUTO'){
        $save = array();
        foreach($this->meta as $fieldname => $props){
          $save[] = $fieldname;
        }
      }
      $input = Input::instance();
      foreach($save as $field){
        $foreach_typefield = &$types->fields->$field->typefield;
        if($types->fields->$field->typefield == 'CheckField' and @$_POST[$field] == ''){
          $_POST[$field] = FALSE;
        }

        if($foreach_typefield == 'PasswordField'){
          $_POST[$field] = fpp::cryptme($_POST[$field]);
        }
        
        if($input->post($field) !== null and $types->fields->$field->typefield <> 'OneToMany' and $types->fields->$field->typefield <> 'TabularModel'){
          $inp = $input->post($field);
          $tmp_inp = $inp;
          if($types->fields->$field->post_exec <> null and request::method() == 'post'){
            $value = $input->post($field);
            eval($types->fields->$field->post_exec.';');
            $inp = $value;
          }
            $update_fields[$field]=$inp;
        }
        
        //Preparando los Uno a muchos, y muchos a muchos

          if($types->fields->$field->typefield == 'OneToMany' or $types->fields->$field->typefield == 'TabularModel'){
               $modtable = substr($types->fields->$field->model,4);
               $metaOTM = fpp::GetOTM($modtable,$this->_Table);               
               $metaOTM['fieldhtml'] = $input->post($field);               
               $metaOTM['pk'] = $field;
               $OneToMany[$field] = $metaOTM;
               $this->db->delete($modtable, array($metaOTM['primary'] => $id));
          }
        }
        /**/

      if($this->_AddKeyField <> null){
        foreach($this->_AddKeyField as $field => $FValue){
          $update_fields[$field]=$FValue;
        }
      }
      if($id <> null){
        $status = $this->db->update($this->_Table,$update_fields, array($first => $id));
      }else{
        $status = $this->db->insert($this->_Table,$update_fields);
        $id = $status->insert_id();
      }

      if(@$_SESSION['PKID'] <> "" AND @$_GET['AJAX_NO_LOAD'] == TRUE){
        $_SESSION['PKID_OTM'] = $id;
      }

      if(is_array($OneToMany)){
        foreach($OneToMany as $valueOTM){
          if(is_array($valueOTM['fieldhtml'])){
            foreach( $valueOTM['fieldhtml'] as $value){
              $arrOTMnew = array($valueOTM['primary']=>$id, $valueOTM['secondary']=>$value );
              $this->db->insert($valueOTM['table'],$arrOTMnew);
            }
          }
        }
      }

        $this->_Response = TRUE;
        $msg = fpp::fppmsg('Guardo Correctamente');
    }
    if($id <> null or $idorigin =='LOOK'){
//Inicializacion del query (construccion & carga)
    $strinTables = implode(',',$arrayTables);
    $select = implode(',',$select);
    $query = $this->db->select($select)->from($strinTables)->limit(1,0);
    if(is_array($arrayWhere)){
      $stringWhere = implode(' AND ',$arrayWhere);
      $query = $query->where($stringWhere);
    }
    if($idorigin <> 'LOOK'){
      $wherearray[] = "$first = $id";
    }

    if($this->_AddKeyField <> null){
      foreach($this->_AddKeyField as $Fkey => $FValue){
        $wherearray[] ="$Fkey = $FValue";
      }
    }
    if($this->_FilterActive <> null){
      foreach($this->_FilterActiveByInfo as $filter => $value){
        $wherearray[] ="{$this->_Table}.{$filter} = $value";
      }
    }
    $where_string = implode(' AND ',$wherearray);
    $query = $query->where($where_string);
    try {
        $rows = $query->get();
    } catch (Exception $e) {
                    echo Kohana::debug('Error: ' ."\n".  $e->getMessage(). "\n");
                    die();
    }    
//escribiendo los campos de acuerdo a sus propiedades
    $data = new StdClass();
    $types->base_uri = $this->base_uri;
    $valid_count = FALSE;
      foreach($rows as $row){
        foreach($OTMSelect as $nameOTM){
          $row->$nameOTM = 'null';
        }
        foreach($row as $name => $value){
        $valid_count = TRUE;
          if($this->_OnlyRead == TRUE){
            $data->$name = $value;
          }else{
            $types->field_value = $value;
//          Si el campo es un "OneToMany"
            if($types->fields->$name->typefield == 'OneToMany' or $types->fields->$name->typefield == 'TabularModel' ){
              if(@$OneToMany[$name]['table']==''){
                $modtable = substr($types->fields->$name->model,4);
                $OneToMany[$name] = fpp::GetOTM($modtable,$this->_Table);
              }
                $OTMArr = null;
//              Tomo el campo primario y secundario

                $OTMdb_field = $OneToMany[$name]['secondary'];
                $OTMdb_pk = $OneToMany[$name]['primary'];
                $valuelistOTM = null;
                try {
                  $valuelistOTM=$this->db->from($OneToMany[$name]['table'])->select($OTMdb_field)->where(array($OTMdb_pk => $id))->get();
                } catch (Exception $e) {
                    echo Kohana::debug('Error: ' ."\n".  $e->getMessage(). "\n");
                    die();
                }
                foreach($valuelistOTM as $rowOTM){
                 $OTMArr[] = $rowOTM->$OTMdb_field;
                }
                $types->field_value = $OTMArr;
            }
            $types->field_name = $name;
            $arrayorder[$name] = $types->ObjectField($name);
          }
        }
        foreach($this->meta as $fieldname => $props){
          $data->$fieldname = $arrayorder[$fieldname];
        }
      }
    }else{
      foreach($items as $name){
          $valid_count = TRUE;
          $types->field_name = $name;
          $types->field_value = NULL;
          $data->$name = $types->ObjectField($name);
      }
    }
    if($valid_count == FALSE){
      return NULL;
    }
    $this->retfields = $data;
    
    //Setting Ajax
    $form = null;
    $attrform = null;
    if(@$_GET['AJAX_NO_LOAD'] == TRUE){
      $form .= '<script>$(document).ready(function(){$(".FORM_AJAX").submit(function(){ return post_ajax(this); })});</script>';
      $attrform = array("class"=>'FORM_AJAX');
    }
    
    $form .= form::open_multipart(NULL,$attrform);
    if($this->GetFieldAjax <> NULL){
      $FAjax = $this->GetFieldAjax;
      return $data->$FAjax;
    }

    $view_info = ($this->_TabView == TRUE) ? 'tabmodel' : 'info';
    $str = View::factory($this->templatedir. $view_info )
            ->set('msg',$msg)
            ->set('data',$data)
            ->set('form',$form)
            ->set('only_read',$this->_OnlyRead)
            ->set('titles',$titles)
            ->set('tblname',$this->_Table)
            ->render();
    return $str;
  }
  
  
  public function JoinRow($KeyFromTable,$RemoteTable,$RemoteKey,$RemoteField){
    $this->_AddField[] = array('localkey'=>$KeyFromTable,'table' => "{$RemoteTable}",'field' => "{$RemoteField}",'key'=>$RemoteKey);
    $this->_AddKeyField["`$RemoteTable`.`$RemoteKey`"] = "`{$this->_Table}`.`{$KeyFromTable}`";
  }
  
  public function AddValueForDefault($field,$value){
    $this->_AddKeyField["{$this->_Table}.$field"] = "{$value}";
  }
  
  public function apply_php($fields,$code){
    $this->_ApplyPHP = TRUE;
    $this->_ApplyPHPFields = $fields;
    $this->_ApplyPHPCode = $code;
  }
  
  private function _apply_php(&$instace){
    if($this->_ApplyPHP == TRUE){
      foreach($this->_ApplyPHPFields as $field){
        $instace->fields->$field->post_exec .= $this->_ApplyPHPCode; 
      }
      $this->_ApplyPHPCode = null;
      $this->_ApplyPHPFields = null;
      $this->_ApplyPHP = FALSE;
    return TRUE;
    }
    return FALSE;
  }
  
  public function Get_Meta(){
    return $this->meta;
  }
  
  public function Get_ListOfMeta(){
    return $this->list_display;
  }
  
  /* REQUIRES SIMPLEMODELER : see -> http://dev.kohanaphp.com/projects/simple-modeler/ */
  public function db2cls($id = null){
  
    $data = array();
    foreach ($this->meta as $key => $value){        
      if($this->_FirstField == null){
          $this->_FirstField = $key;
      }
      $data[$key] = '';
    }
    $cls = new stdClass();
    $cls->table_name = $this->_Table;
    $cls->limit = $this->items;
    $cls->primary_key = $this->_FirstField; //Firstfield as PK ...
    $cls->data = $data;
    $db2cls = new Kfppcls2db($cls,$id);
    return $db2cls;
  }
  
}
